package com.emex.app.stuff.gui;

import com.emex.app.shared.data.OrderPosition;
import com.emex.app.shared.data.Position;
import com.emex.app.shared.data.enums.OrderPositionStatus;
import com.emex.app.stuff.constant.IdentifierConstants;
import com.emex.app.stuff.gui.model.OrderPositionTableModel;
import com.emex.app.stuff.gui.model.PositionTableModel;
import com.emex.app.stuff.provider.ShopDataProvider;
import com.emex.app.stuff.utils.StringUtilities;
import com.emex.app.stuff.utils.UIUtils;
import java.util.ArrayList;
import java.util.List;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

/**
 *
 * @author Sergey Karavaev
 */
public class SearchPositionDialog extends javax.swing.JDialog {

    private Position currentlyFoundPosition;
    private PositionTableModel positionTableModel;
    List<Position> empty = new ArrayList<>();
    private OrderPositionTableModel orderPositionTableModel;

    /**
     * Creates new form SearchPositionDialog
     */
    public SearchPositionDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        positionsTable.setModel(new PositionTableModel(empty));
        positionsTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                int row = positionsTable.getSelectedRow();
                if ((row >= 0) && (row < positionsTable.getRowCount())) {
                    addToOrderButton.setEnabled(true);
                } else {
                    addToOrderButton.setEnabled(false);
                }
            }
        });
    }

    public OrderPositionTableModel getOrderPositionTableModel() {
        return orderPositionTableModel;
    }

    public void setOrderPositionTableModel(OrderPositionTableModel orderPositionTableModel) {
        this.orderPositionTableModel = orderPositionTableModel;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        searchPanel = new javax.swing.JPanel();
        searchField = new org.jdesktop.swingx.JXSearchField();
        addToOrderButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        positionsTable = new org.jdesktop.swingx.JXTable();
        cancelButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle(org.openide.util.NbBundle.getMessage(SearchPositionDialog.class, "SearchPositionDialog.title")); // NOI18N

        searchPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(SearchPositionDialog.class, "SearchPositionDialog.searchPanel.border.title"))); // NOI18N

        searchField.setText(org.openide.util.NbBundle.getMessage(SearchPositionDialog.class, "SearchPositionDialog.searchField.text")); // NOI18N
        searchField.setSearchMode(org.jdesktop.swingx.JXSearchField.SearchMode.REGULAR);
        searchField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchFieldActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout searchPanelLayout = new javax.swing.GroupLayout(searchPanel);
        searchPanel.setLayout(searchPanelLayout);
        searchPanelLayout.setHorizontalGroup(
            searchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(searchPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(searchField, javax.swing.GroupLayout.DEFAULT_SIZE, 348, Short.MAX_VALUE)
                .addContainerGap())
        );
        searchPanelLayout.setVerticalGroup(
            searchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(searchPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(searchField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        addToOrderButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/add.png"))); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(addToOrderButton, org.openide.util.NbBundle.getMessage(SearchPositionDialog.class, "SearchPositionDialog.addToOrderButton.text")); // NOI18N
        addToOrderButton.setEnabled(false);
        addToOrderButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addToOrderButtonActionPerformed(evt);
            }
        });

        positionsTable.setToolTipText(org.openide.util.NbBundle.getMessage(SearchPositionDialog.class, "SearchPositionDialog.positionsTable.toolTipText")); // NOI18N
        positionsTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                positionsTableMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(positionsTable);

        org.openide.awt.Mnemonics.setLocalizedText(cancelButton, org.openide.util.NbBundle.getMessage(SearchPositionDialog.class, "SearchPositionDialog.cancelButton.text")); // NOI18N
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(searchPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(addToOrderButton)
                        .addGap(0, 61, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(cancelButton)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(addToOrderButton)
                    .addComponent(searchPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 281, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(cancelButton)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void searchFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchFieldActionPerformed
        String code = searchField.getText();
        if (null != code && !code.isEmpty()) {
            String formattedCode = StringUtilities.formatPositionCode(StringUtilities.formatStringFromSpecialCharacters(code)).toUpperCase();
            searchField.setText(formattedCode);
            List<Position> positions = ShopDataProvider.getInstance().getPositionByCode(formattedCode);
            if (positions == null || positions.isEmpty()) {
                positionsTable.setModel(new PositionTableModel(empty));
                UIUtils.showInfoMessage("Позиция не найдена");
            } else {
                currentlyFoundPosition = positions.get(0);
                List<Position> pos = ShopDataProvider.getInstance().getCrossPositionsByPositionId(currentlyFoundPosition.getId());
                pos.add(currentlyFoundPosition);
                positionTableModel = new PositionTableModel(pos);
                positionsTable.setModel(positionTableModel);
            }
        }
    }//GEN-LAST:event_searchFieldActionPerformed

    private void addToOrderButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addToOrderButtonActionPerformed
        Position selection = getPositionSelection();
        if (null != selection) {
            if (selection.getAmount() == 0) {
                UIUtils.showInfoMessage("В данный момент позиция отсутствует на складе");
                return;
            }
            OrderPosition op = new OrderPosition();
            op.setAmount(1);
            op.setName(selection.getName() + " " + selection.getIssuer() + " " + selection.getCode());
            op.setPrice(selection.getPrice());
            op.setPurPrice(selection.getPurPrice());
            op.setStatus(OrderPositionStatus.ISSUED.ordinal());
            op.setPosition(selection);
            op.setProviderId(IdentifierConstants.SHOP_EXISTING_POSITION);

            if (null != orderPositionTableModel) {
                orderPositionTableModel.dataAdded(op);
            }
        }
    }//GEN-LAST:event_addToOrderButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        setVisible(false);
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void positionsTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_positionsTableMouseClicked
        if (evt.getClickCount() == 2) {
            addToOrderButtonActionPerformed(null);
        }
    }//GEN-LAST:event_positionsTableMouseClicked

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(SearchPositionDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(SearchPositionDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(SearchPositionDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(SearchPositionDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                SearchPositionDialog dialog = new SearchPositionDialog(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addToOrderButton;
    private javax.swing.JButton cancelButton;
    private javax.swing.JPanel findPanel;
    private javax.swing.JPanel findPanel1;
    private javax.swing.JPanel findPanel2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private org.jdesktop.swingx.JXTable positionsTable;
    private org.jdesktop.swingx.JXSearchField searchField;
    private javax.swing.JPanel searchPanel;
    // End of variables declaration//GEN-END:variables

    protected Position getPositionSelection() {
        if (positionsTable.getSelectedRow() > -1) {
            Position pos = (Position) positionsTable
                    .getValueAt(positionsTable.getSelectedRow(), -1);
            return pos;
        }
        return null;
    }
}
